package org.seefly.iprint.controller;

import org.seefly.iprint.entity.OrderItem;
import org.seefly.iprint.entity.Orders;
import org.seefly.iprint.entity.User;
import org.seefly.iprint.service.OrderService;
import org.seefly.iprint.utils.PDFUtils;
import org.seefly.iprint.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 订单流程模块
 * @author liujianxin
 * @date 2018年3月30日 上午8:56:31
 * @version 1.0.0
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    private OrderService service;
    public OrderController(OrderService service) {
        this.service = service;
    }

    /**文档上传地址*/
    @Value("${user.upload.docaddr}")
    private String docUploadAddr;
    /**订单在session域中的key*/
    @Value("${user.order.orderItems}")
    private String orderItem;
    /**订单项购物车在session中的key*/
    @Value("${user.order.cart}")
    private String orderCart;
    /**文档打印*/
    @Value("${print.type.doc}")
    private String docPrint;
    
    
    private HashMap<String,String> pathMap = null;
    private HashMap<String,String> addrMap = null;
    private HashMap<String,String> cartMap = null;
    @PostConstruct
    public void initMethod() {
        //上传页面视图地址
        this.pathMap = new HashMap<>();
        pathMap.put("document", "front/docupload");
        pathMap.put("photo", "front/photoupload");
        pathMap.put("idphoto", "front/idphotoupload");
        pathMap.put("leaflet", "front/leafletupload");
        //上传文件地址
        this.addrMap = new HashMap<>();
        addrMap.put("photo", "G:\\upload\\iprint\\photo\\");
        addrMap.put("document", "G:\\upload\\iprint\\document\\");
        addrMap.put("idphoto", "G:\\upload\\iprint\\idphoto\\");
        addrMap.put("leaflet", "G:\\upload\\iprint\\leaflet\\");
        //购物车视图地址
        this.cartMap = new HashMap<>();
        cartMap.put("photo", "front/photoCart");
        cartMap.put("document", "front/docCart");
        cartMap.put("idphoto", "front/idphotoCart");
        cartMap.put("leaflet", "front/leafletCart");
    }
    
    /**
     * 获取文件上传页面
     * @return 文件上传页面视图逻辑地址
     */
    @RequestMapping("/upload")
    public String document(OrderItem oi, HttpSession session) {
        // 查询价格
        BigDecimal price = service.findPrice(oi);
        //查询额外服务价格：装订方式、照片换底等
        BigDecimal serviced = service.findServicedPrice(oi);
        oi.setUnitPrice(serviced);
        oi.setPagePrice(price);
        session.setAttribute(orderItem, oi);
        //需求： 根据title返回不同的视图
        return this.pathMap.get(oi.getTitle());
    }
    
    

    /**
     * 
     * @Description (文件上传，保存文档订单项到'购物车')
     * @param session
     * @return 异步上传json信息
     * @throws Exception
     */
    @RequestMapping("/doUpload")
    @ResponseBody
    public String uploadDoc(MultipartFile file, HttpSession session) throws Exception {
        // 判断域中有无商品页面所选参数
        OrderItem template = (OrderItem) session.getAttribute(orderItem);
        if (template == null) {
            return "{\"code\":1}";
        }
        // 获取购物车
        @SuppressWarnings("unchecked")
        ArrayList<OrderItem> list = (ArrayList<OrderItem>) session.getAttribute(orderCart);
        if (list == null) {
            list = new ArrayList<>();
            session.setAttribute(orderCart, list);
        }
        // 复制参数模板，放入购物车，填充参数
        OrderItem item = (OrderItem) template.clone();
        list.add(item);
        // 获取文件名
        String realname = file.getOriginalFilename();
        // 设置文件名
        item.setFileName(realname);
        // 获取随机名
        String fileaddr = this.addrMap.get(item.getTitle()) + UUIDUtils.getUUIDName(realname);
        // 将文件保存到硬盘
        file.transferTo(new File(fileaddr));
        // 设置文件地址
        item.setFileAddr(fileaddr);
        // 设置文档总页数 
        if(realname.endsWith(".pdf")) {
            item.setPageCount(PDFUtils.getPDFPageCount(fileaddr));
        }
        // 设置商品标题
        //doc.setTitle(docPrint);应该在前端传
        
        return "{\"code\":0}";
    }

    
    
    /**
     * @Description (返回购物车视图地址)
     * @return
     */
    @RequestMapping("/cart")
    public String getCart(HttpSession session) {
        OrderItem template = (OrderItem) session.getAttribute(orderItem);
        if (template == null) {
            return "404";
        } 
        //根据title返回不同视图
        return this.cartMap.get(template.getTitle());
    }

    /**
     * @Description (提交订单，发起付款，持久化订单以及订单项到数据库)
     * @param payType  支付类型
     * @param userMsg   用户留言
     * @param session  
     * @return  支付页面视图地址
     */
    @RequestMapping("/pay")
    public String createDocOrder(String payType,String userMsg,HttpSession session) {
        User user = (User) session.getAttribute("user");
        if(user == null) {
            return "404";
        }
        
        // 先创建订单
        Orders od = new Orders();
        //设置ID,用户留言,支付类型
        od.setUserId(user.getId());
        od.setUserMsg(userMsg);
        od.setPayType(payType);
        od.setStatus("1");
        //获取购物车
        @SuppressWarnings("unchecked")
        ArrayList<OrderItem> list = (ArrayList<OrderItem>) session.getAttribute(orderCart);
        // 再填充订单
        BigDecimal total = new BigDecimal(0);
        for(OrderItem e : list) {
            total = total.add(e.getTotal());
        }
        // 设置订单总金额
        od.setTotal(total);
        // 先持久化订单
        service.addOrder(od);
        // 再持久化订单项
        for(OrderItem e : list) {
            e.setOrderId(od.getId());
            service.addOrderItem(e);
        }
        // 调用端口付款
        System.out.println("++++++++++++++++++++++++++++调用付款接口+++++++++++++++++++++++++++++++");
        return "forward:/index";
    }
    
   
}
